package com.controller;

import com.entity.Job;
import com.util.DataSourceUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/job")
public class JobServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<Job> job1s = new ArrayList<>();
        String sql = "select * from Job2";
        try (Connection con = DataSourceUtils.getConnection();
             PreparedStatement ps = con.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()
        ) {
            while (rs.next()) {
                Job job1 = new Job(rs.getString("jid"), rs.getString("Title"), rs.getObject("PublishDate", LocalDateTime.class), rs.getString("Content"), rs.getString("ImageURL"));
                job1s.add(job1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        req.setAttribute("job1s", job1s);
        List<Job> jobs = new ArrayList<>();
        String sql2 = "select * from Job";
        try (Connection con = DataSourceUtils.getConnection();
             PreparedStatement ps = con.prepareStatement(sql2);
             ResultSet rs = ps.executeQuery()
        ) {
            while (rs.next()) {
                Job job = new Job(rs.getString("jid"), rs.getString("Title"), rs.getObject("PublishDate", LocalDateTime.class), rs.getString("Content"), rs.getString("ImageURL"));
                jobs.add(job);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        req.setAttribute("jobs", jobs);
        req.getRequestDispatcher("/WEB-INF/jsp/job.jsp").forward(req, resp);
    }
}